package com.gage.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gage.controller.base.BaseController;
import com.gage.commons.result.PageInfo;
import com.gage.model.shiro.ShiroUser;
import com.gage.commons.utils.StringUtils;
import com.gage.model.BaseComboBox;
import com.gage.model.CmsCatalog;
import com.gage.model.SysBaseDict;
import com.gage.service.ICmsCatalogService;
import com.gage.service.ISysDictService;
@Controller
@RequestMapping({ "/catalog"})
public class CmsCatalogController extends BaseController{
	@Autowired
	private ICmsCatalogService cmsCatalogService;
	@Autowired
	private ISysDictService sysDictService;
	@RequestMapping("/index")
	public String index(HttpServletRequest request, Model model)
	{
		return "/admin/catalog/index";
	}
	/**
	 * 加载树
	 * @author lkr
	 * @date:20170512
	 * @param request
	 * @param id
	 * @return
	 */
	@PostMapping("/tree")
    @ResponseBody
	public Object getCatalogTree(HttpServletRequest request,String id)
	{
		if (StringUtils.isBlank(id))
		{
			id = "daydayup_cms";
		}
		String catalogType="association";
		System.out.println(id);
		return cmsCatalogService.getCatalogTreeByParentIdAndType(id,null);
	}
	/**
	 * 栏目列表
     * @author lkr
     * @date:20170512
	 * @param catalog
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @return
	 */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(CmsCatalog catalog, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        System.out.println("*****pid********"+catalog.getParentId());
        if (StringUtils.isNotEmpty(catalog.getParentId())) {
            condition.put("parentId", catalog.getParentId());
        }else {
        	 condition.put("parentId", "0");
		}
        condition.put("associationId", 0);
        pageInfo.setCondition(condition);
        return cmsCatalogService.selectDataGrid(pageInfo);
    }
    /**移动树
     * @author lkr
     * @date:20170512
     * @param dictcode
     * @param parentid
     * @return
     */
    @PostMapping("/move")
    @ResponseBody 
	public Object move(String catalogcode,String parentid){		
		if (StringUtils.isNotEmpty(catalogcode)&&StringUtils.isNotEmpty(parentid)){
			int n=cmsCatalogService.updateMoveCatalog(catalogcode,parentid);
			if (n==0){
				return renderSuccess("移动失败！");
			}
			return renderSuccess("移动成功！");
		}else {
			return renderSuccess("网络异常！");
		}
	}
    /**
     * 添加数据字典页
      * @author lkr
      * @date:20170512
     * @return
     */
    @GetMapping("/add")
    public String addPage(Model model) {
    	List<SysBaseDict> dictList=new ArrayList<>() ;
    	SysBaseDict baseDict1=new SysBaseDict();
    	baseDict1.setDictcode("admin");
    	baseDict1.setDictname("平台系统栏目");
    	SysBaseDict baseDict2=new SysBaseDict();
    	baseDict2.setDictcode("association");
    	baseDict2.setDictname("社团系统栏目");
    	dictList.add(baseDict1);
    	dictList.add(baseDict2);
    	model.addAttribute("dictList", dictList);
        return "admin/catalog/edit";
    }
    /**
     * 编辑数据字典页
     *
     * @return
     */
    @GetMapping("/edit")
    public String editPage(String id,Model model) {
    	CmsCatalog catalog=null;
    	if (StringUtils.isNotEmpty(id)) {
    		catalog=	cmsCatalogService.loadCatalogByCatalogCode(id);
    		String parentId=catalog.getParentId();
    		if (StringUtils.isEmpty(parentId)) {
    			catalog.setParentId("0");
			}
		}
    	List<SysBaseDict> dictList=new ArrayList<>() ;
    	SysBaseDict baseDict1=new SysBaseDict();
    	baseDict1.setDictcode("admin");
    	baseDict1.setDictname("平台系统栏目");
    	SysBaseDict baseDict2=new SysBaseDict();
    	baseDict2.setDictcode("association");
    	baseDict2.setDictname("社团系统栏目");
    	dictList.add(baseDict1);
    	dictList.add(baseDict2);
    	model.addAttribute("dictList", dictList);
    	model.addAttribute("catalog", catalog);
        return "admin/catalog/edit";
    }
    /**
     * @author lkr
     * @date:20170512
     * @param catalog
     * @param result
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
	public Object save(@Valid CmsCatalog catalog,String oldId,String oldCode, BindingResult result)
	{
    	int status=0;
		ShiroUser u = this.getShiroUser();
		CmsCatalog catalogs = cmsCatalogService.loadCatalogByCatalogCode(catalog.getCatalogCode());
			if (StringUtils.isEmpty(catalog.getId()))
			{
				if (StringUtils.isEmpty(catalogs))
				{	
					if (StringUtils.isEmpty(catalog.getParentId())) {
						catalog.setCatalogLevel(1);
						catalog.setParentId("0");
					}
					catalog.setAssociationId(0);//默认0是系统文章
					catalog.setCreateUid(u.getId().toString());
					catalog.setUpdateDate(new Date());
					catalog.setInsertDate(new Date());
					status=cmsCatalogService.insertSelective(catalog);
				} else
				{
					return resultJson("0","栏目编码已存在！","");
				}
			} else
			{
				if (StringUtils.isNotEmpty(catalogs)) {
					String pId=catalogs.getId().toString();
					if (!oldId.equals(pId)) {
						return resultJson("0","栏目编码已存在！","");
					}
				}
				catalog.setUpdateDate(new Date());
				catalog.setUpdateUid(u.getId().toString());
				status=cmsCatalogService.updateByCatalogCodeSelective(catalog);
				List<CmsCatalog> catalogList=cmsCatalogService.findCatalogByPidAndType(oldCode,null);
				if (catalogList.size()>0) {
					for (CmsCatalog pCatalog:catalogList) {
						pCatalog.setParentId(catalog.getCatalogCode());
						cmsCatalogService.updateByCatalogCodeSelective(pCatalog);
					}
				}
			}
			return resultJson("1","信息保存成功","");
	}
    /**
     * 删除栏目
     * @author lkr
 	 * @date:20170512
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
    	int count=0;
    	String[] ids = id.split(",");
    	List<String> list = new ArrayList<String>();
		for (int i = 0; i < ids.length; i++){
			count=cmsCatalogService.findCatalogByPidAndType(ids[i],null).size();
	    	if (count>0) {
	    		CmsCatalog catalog=cmsCatalogService.loadCatalogByCatalogCode(ids[i]);
	    		return renderSuccess("该"+catalog.getCatalogName()+"栏目存在子栏目，不能删除！");
			}else {
				list.add(ids[i].trim());
			}
		}
		
		if (this.cmsCatalogService.removeCatalog(list))
		{
			return renderSuccess("成功删除"+ids.length+"条信息！");
		} else
		{
			return renderError("删除失败，删除操作出错！");
		}
       // sysDictService.deleteUserById(id);
    }
}
